package com.start.common.enums;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.start.common.tools.StartEnumTools;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class IntegerToEnumConvertFactory extends JsonDeserializer<StartBaseIntegerEnum> implements ConverterFactory<Integer, StartBaseIntegerEnum> {
    private static final Map<Class, Converter> CONVERTERS = new HashMap<>();

    @Override
    public <T extends StartBaseIntegerEnum> Converter<Integer, T> getConverter(Class<T> clazz) {
        Converter<Integer, T> converter = CONVERTERS.get(clazz);
        if (converter == null) {
            converter = new IntegerToEnumConvert(clazz);
            CONVERTERS.put(clazz, converter);
        }
        return converter;
    }


    @Override
    public StartBaseIntegerEnum deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        JsonNode node = p.getCodec().readTree(p);
        String currentName = p.currentName();
        Object currentValue = p.getCurrentValue();
        Class findPropertyType = null;
        findPropertyType = BeanUtils.findPropertyType(currentName, currentValue.getClass());
        if (findPropertyType == null) {
            log.info("在" + currentValue.getClass() + "实体类中找不到" + currentName + "字段");
            return null;
        }
        Integer asText = node.asInt();
        return StartEnumTools.findEnumByValue(findPropertyType, asText);

    }
}
